package bm.com.project.server.organization.service.impl;

import bm.com.framework.common.config.EnumCode;
import bm.com.framework.common.exception.BmException;
import bm.com.framework.security.util.SecurityUtils;
import bm.com.project.server.common.dto.SearchBaseDTO;
import bm.com.project.server.organization.dto.BmOrgMemberDTO;
import bm.com.project.server.organization.dto.VoBmOrgMemberDTO;
import bm.com.project.server.organization.entity.*;
import bm.com.project.server.organization.mapper.*;
import bm.com.project.server.organization.service.MemberService;
import bm.com.project.server.sys.entity.BmSysUserEntity;
import bm.com.project.server.sys.mapper.BmSysUserMapper;
import bm.com.framework.common.resp.PageVO;
import bm.com.framework.common.resp.ResultVO;
import bm.com.framework.common.unit.DateUnit;
import bm.com.framework.redis.unit.RedisUnits;
import bm.com.framework.common.unit.Tool;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
public class MemberServiceImpl extends ServiceImpl<BmOrgMemberMapper, BmOrgMemberEntity> implements MemberService {

    @Autowired
    BmOrgMemberMapper bmOrgMemberDao;

    @Autowired
    BmOrgDepartmentMapper bmOrgDepartmentDao;

    @Resource
    BmSysUserMapper bmSysUserDao;

    @Autowired
    BmOrgMapper bmOrgDao;

    @Autowired
    BmOrgMemberInviteMapper bmOrgMemberInviteDao;

    @Autowired
    BmOrgMemberInviteRecordMapper bmOrgMemberInviteRecordDao;

    @Autowired
    RedisUnits redisUnits;

    /**
     * 成员列表
     *
     * @param queue
     * @return
     */
    @Override
    public PageVO<VoBmOrgMemberDTO> getList(SearchBaseDTO queue) {

        if (queue.getPageNum() <= 1) {
            queue.setPageNum(1);
        }


        queue.setPageOffset((queue.getPage() - 1) * queue.getPageNum());
        queue.setOrgId(SecurityUtils.getOrgId());
        List<VoBmOrgMemberDTO> bmOrgDepartmentDaoIPage = bmOrgMemberDao.getOrgMembersBySearch(queue);
        Integer count = bmOrgMemberDao.getOrgMembersBySearchCount(queue);
        return new PageVO<>(count, bmOrgDepartmentDaoIPage);

    }

    /**
     * 成员详情
     *
     * @param departmentId
     * @return
     */
    @Override
    public BmOrgMemberEntity getDetail(String departmentId) {
        return bmOrgMemberDao.selectById(departmentId);
    }

    /**
     * 获取邀请成员链接
     *
     * @param orgId
     * @param userId
     * @param limitNum
     * @return
     */
    @Override
    public ResultVO getInviteLink(String orgId, String userId, int limitNum) {

        BmOrgEntity bmOrgEntity = bmOrgDao.selectById(orgId);
        if (Tool.isObjectEmpty(bmOrgEntity) || bmOrgEntity.getStatus() != 1) {
            return ResultVO.error("该组织已无效");
        }

        BmOrgMemberInviteEntity bmOrgMemberInviteEntity = new BmOrgMemberInviteEntity();
        String inviteCode = Tool.getRoundString(1, 16, false);

        /** 默认有效期为两天 */
        long validityDate = DateUnit.getDateZeroSecond(EnumCode.TIME_86400 * 2);

        /** 保存邀请连诶实体信息 */
        bmOrgMemberInviteEntity.setOrgId(orgId);
        bmOrgMemberInviteEntity.setInviterId(userId);
        bmOrgMemberInviteEntity.setStatus(1);
        bmOrgMemberInviteEntity.setLimitNum(limitNum);
        bmOrgMemberInviteEntity.setResidueNum(limitNum);
        bmOrgMemberInviteEntity.setInviteCode(inviteCode);
        bmOrgMemberInviteEntity.setValidityDate(validityDate);
        bmOrgMemberInviteEntity.setCreateDate(DateUnit.getNowTimeSecond());
        bmOrgMemberInviteDao.insert(bmOrgMemberInviteEntity);

        HashMap<String, String> link = new HashMap<>();
        link.put("code", inviteCode);
        link.put("validityDate", String.valueOf(validityDate));

        return ResultVO.success(link);
    }

    /**
     * 通过邀请码加入组织
     *
     * @param userId
     * @param inviteCode
     * @return
     */
    @Override
    public ResultVO joinOrg(String userId, String inviteCode) {

        QueryWrapper<Object> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("inviteCode", inviteCode);

        /** 判断邀请码的有效性 */
        BmOrgMemberInviteEntity bmOrgMemberInviteEntity = bmOrgMemberInviteDao.selectOne(queryWrapper);
        if (Tool.isObjectEmpty(bmOrgMemberInviteEntity) || bmOrgMemberInviteEntity.getResidueNum() == 0) {
            return ResultVO.error("无效的邀请码");
        }

        if (bmOrgMemberInviteEntity.getValidityDate() > DateUnit.getNowTimeSecond()) {
            return ResultVO.error("邀请码已过有效期");
        }

        BmOrgMemberInviteRecordEntity recordEntity = new BmOrgMemberInviteRecordEntity();
        recordEntity.setAccepterId(userId);
        recordEntity.setOrgId(bmOrgMemberInviteEntity.getOrgId());
        recordEntity.setStatus(2);
        recordEntity.setInviteId(bmOrgMemberInviteEntity.getId());
        recordEntity.setCreateDate(DateUnit.getNowTimeSecond());

        bmOrgMemberInviteRecordDao.insert(recordEntity);
        return ResultVO.success("操作成功，请等待组织的审核");
    }

    /**
     * 组织成员邀请审核
     *
     * @param inviteRecordId
     * @param departmentId
     * @param isCheck
     * @return
     */
    @Override
    public ResultVO checkInvite(String inviteRecordId, String departmentId, int isCheck) {
        BmOrgMemberInviteRecordEntity recordEntity = bmOrgMemberInviteRecordDao.selectById(inviteRecordId);
        if (recordEntity.getIsCheck() == 1) {
            return ResultVO.error("该申请记录已审核过");
        }

        BmOrgMemberEntity orgUser = bmOrgMemberDao.getOrgUser(recordEntity.getOrgId(), recordEntity.getAccepterId());
        if (!Tool.isObjectEmpty(orgUser)) {
            return ResultVO.error("该邀请者已存在组织中");
        }

        /** 同意加入 */
        if (isCheck == 1) {
            BmOrgMemberInviteEntity inviteEntity = bmOrgMemberInviteDao.selectById(recordEntity.getInviteId());
            int ResidueNum = inviteEntity.getResidueNum() - 1;
            if (ResidueNum < 0) {
                ResidueNum = 0;
            }
            inviteEntity.setResidueNum(ResidueNum);

            QueryWrapper<Object> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("id", recordEntity.getInviteId());
            bmOrgMemberInviteDao.update(inviteEntity, queryWrapper);

            recordEntity.setStatus(1);
            recordEntity.setAcceptDate(DateUnit.getNowTimeSecond());

            /** 保存信息到组织成员中 */
            BmOrgMemberEntity bmOrgMemberEntity = new BmOrgMemberEntity();
            bmOrgMemberEntity.setOrgId(recordEntity.getOrgId());
            bmOrgMemberEntity.setStatus(1);
            bmOrgMemberEntity.setUserId(recordEntity.getAccepterId());
            bmOrgMemberEntity.setCreateDate(DateUnit.getNowTimeSecond());
            bmOrgMemberDao.insert(bmOrgMemberEntity);

        } else {
            recordEntity.setStatus(3);
            recordEntity.setRefuseDate(DateUnit.getNowTimeSecond());
        }
        recordEntity.setIsCheck(isCheck);

        /** 更新邀请记录信息 */
        bmOrgMemberInviteRecordDao.updateById(inviteRecordId);

        return ResultVO.success("操作成功");
    }

    /**
     * 通过手机号批量导入
     *
     * @param mobiles
     * @return
     */
    @Override
    @Transactional
    public ResultVO batchImport(String mobiles) {

        if (Tool.isStringEmpty(mobiles) || mobiles.length() < 11) {
            return ResultVO.error("无效的手机号");
        }

        List<String> errorMobile = new ArrayList();

        try {

            String[] splitMobile = mobiles.split("#");
            QueryWrapper<BmOrgDepartmentEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("orgId", SecurityUtils.getOrgId());
            queryWrapper.eq("type", 1);

            /** 获取系统默认创建的部门 */
            BmOrgDepartmentEntity bmOrgDepartment = bmOrgDepartmentDao.selectOne(queryWrapper);

            long time = DateUnit.getNowTimeSecond();

            ArrayList<BmSysUserEntity> bmSysUsers = new ArrayList<>(); //系统用户数据
            ArrayList<BmOrgMemberEntity> bmOrgMembers = new ArrayList<>(); //组织成员信息

            /** 组装数据 */
            for (String str : splitMobile) {

                System.out.println(str);
                if (str.length() == 11) {
                    long mobile = Long.valueOf(str);
                    String username = "半亩用户-" + str.substring(6, 11);
                    String userId = Tool.iDGenerator();
                    System.out.println("用户自增id：" + userId);

                    BmSysUserEntity bmSysUserEntity = new BmSysUserEntity();
                    bmSysUserEntity.setId(userId);
                    bmSysUserEntity.setUsername(username);
                    bmSysUserEntity.setMobile(mobile);
                    bmSysUserEntity.setPassword("000000");
                    bmSysUserEntity.setStatus(1);
                    bmSysUserEntity.setCreateDate(time);
                    bmSysUserEntity.setUpdateDate(time);
                    bmSysUsers.add(bmSysUserEntity);

                    /** 保存组织成员信息 */
                    String memberId = Tool.iDGenerator();
                    BmOrgMemberEntity bmOrgMemberEntity = new BmOrgMemberEntity();
                    bmOrgMemberEntity.setId(memberId);
                    bmOrgMemberEntity.setUserId(userId);
                    bmOrgMemberEntity.setDepartmentId(bmOrgDepartment.getId());
                    bmOrgMemberEntity.setOrgId(SecurityUtils.getOrgId());
                    bmOrgMemberEntity.setIsManager(1);
                    bmOrgMemberEntity.setCreateDate(time);

                    bmOrgMembers.add(bmOrgMemberEntity);

                } else {
                    errorMobile.add(str);
                }
            }

            /** 批量添加系统用户 */
            bmSysUserDao.saveBatch(bmSysUsers);

            /** 批量添加数据 */
            saveBatch(bmOrgMembers);
        } catch (BmException e) {
            return ResultVO.error(e.getMessage());
        }
        return ResultVO.success("批量添加成功");
    }

    /**
     * 编辑成员信息
     * @param bmOrgMember
     * @return
     */
    @Override
    public ResultVO edit(BmOrgMemberDTO bmOrgMember) {

        if (Tool.isStringEmpty(bmOrgMember.getId()) || Tool.isStringEmpty(bmOrgMember.getDepartmentId())) {
            return ResultVO.error("参数不能为空");
        }

        BmOrgMemberEntity bmOrgMemberEntity = bmOrgMemberDao.selectById(bmOrgMember.getId());
        if (Tool.isObjectEmpty(bmOrgMemberEntity) || bmOrgMemberEntity.getStatus() == 2) {
            return ResultVO.error("无效的成员信息");
        }

        /** 编辑组织成员信息 */
        bmOrgMemberEntity.setJob(bmOrgMember.getJob());
        bmOrgMemberEntity.setDepartmentId(bmOrgMember.getDepartmentId());
        bmOrgMemberEntity.setStatus(bmOrgMember.getStatus());
        bmOrgMemberEntity.setIsManager(bmOrgMember.getIsManager());
        bmOrgMemberEntity.setRemark(bmOrgMember.getRemark());
        updateById(bmOrgMemberEntity);

        return ResultVO.success("操作成功");

    }

    @Override
    public ResultVO setManager(String memberId, int isManager) {

        if (Tool.isStringEmpty(memberId)) {
            return ResultVO.error("参数不能为空");
        }

        BmOrgMemberEntity bmOrgMemberEntity = bmOrgMemberDao.selectById(memberId);
        bmOrgMemberEntity.setIsManager(isManager);
        bmOrgMemberDao.updateById(bmOrgMemberEntity);
        return ResultVO.success("设置成功");
    }
}
